var createError = require('http-errors');
var express = require('express');
var path = require('path');
var FileStreamRotator = require('file-stream-rotator');
var fs = require('fs');
var logger = require('morgan');
var app = express();
var path = require('path');
var cookieParser = require('cookie-parser');
var indexRouter = require('./routes/index');
var uploadFile = require('./ueditor/upfile');
var config = require("./ueditor/config");
var logDirectory = __dirname + '/log';

//确定文件路径存在
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);

//创建写入流
var accessLogStream = FileStreamRotator.getStream({
  date_format: 'YYYYMMDD',
  filename: logDirectory + '/%DATE%.log',
  frequency: 'daily',
  verbose: false
});

//设置日志
app.use(logger('combined', {stream: accessLogStream}));

//设置模板引擎
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

//这个目录作为返回静态文件的根目录，还有html文件需要加载的静态文件目录
app.use(express.static(path.join(__dirname, '../dist')));

//数据请求路由,增删查改的接口
app.use('/interface', require("./routes/interface"));

//ueditor的接口
app.post("/editor/controller", uploadFile.upload_file);
app.get("/editor/controller", function(req, res, next){ res.json(config); });

//ui的路由
app.use('/personal', require('./routes/personal.js'));
app.use('/management', require('./routes/management.js'));
app.use('/', indexRouter);
// 当是不知道的路由的时候都返回首页
app.get(/\.*/, function(req, res, next) {
  console.log("未知路由匹配到根目录");
  res.render('index', { title: '航程' });
});

// catch 404 and forward to error handler
app.use(function(req, res, next) { next(createError(404)); });

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
